<template>
  <ContentWrap>
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card class="text-center">
        <div class="text-2xl font-bold text-blue-600">{{ stats.totalFeedbacks }}</div>
        <div class="text-gray-500">总反馈数</div>
      </el-card>
      <el-card class="text-center">
        <div class="text-2xl font-bold text-orange-600">{{ stats.pendingFeedbacks }}</div>
        <div class="text-gray-500">待处理</div>
      </el-card>
      <el-card class="text-center">
        <div class="text-2xl font-bold text-green-600">{{ stats.handledFeedbacks }}</div>
        <div class="text-gray-500">已处理</div>
      </el-card>
      <el-card class="text-center">
        <div class="text-2xl font-bold text-purple-600">{{ stats.todayNewFeedbacks }}</div>
        <div class="text-gray-500">今日新增</div>
      </el-card>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-4">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索反馈内容或联系方式"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="反馈类型">
          <el-select v-model="searchForm.type" placeholder="选择类型" clearable style="width: 150px">
            <el-option label="Bug反馈" value="bug" />
            <el-option label="功能建议" value="suggestion" />
            <el-option label="投诉" value="complaint" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="未处理" :value="0" />
            <el-option label="处理中" :value="1" />
            <el-option label="已处理" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 反馈列表 -->
    <el-card>
      <el-table v-loading="loading" :data="feedbackList" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="feedbackType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.feedbackType)">{{ getTypeLabel(row.feedbackType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="反馈内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="contactInfo" label="联系方式" width="150" show-overflow-tooltip />
        <el-table-column prop="platform" label="平台" width="80" />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="180" />
        <el-table-column prop="handleTime" label="处理时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 0" 
              type="success" 
              size="small" 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center mt-4">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="反馈详情" width="600px">
      <div v-if="currentFeedback">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="反馈ID">{{ currentFeedback.id }}</el-descriptions-item>
          <el-descriptions-item label="反馈类型">
            <el-tag :type="getTypeTagType(currentFeedback.feedbackType)">
              {{ getTypeLabel(currentFeedback.feedbackType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系方式" span="2">{{ currentFeedback.contactInfo }}</el-descriptions-item>
          <el-descriptions-item label="平台">{{ currentFeedback.platform }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ currentFeedback.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentFeedback.status)">
              {{ getStatusLabel(currentFeedback.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ currentFeedback.createTime }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentFeedback.handleTime || '未处理' }}</el-descriptions-item>
          <el-descriptions-item label="反馈内容" span="2">
            <div class="whitespace-pre-wrap">{{ currentFeedback.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.remark" label="处理备注" span="2">
            <div class="whitespace-pre-wrap">{{ currentFeedback.remark }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 处理对话框 -->
    <el-dialog v-model="processVisible" title="处理反馈" width="500px">
      <el-form :model="processForm" label-width="80px">
        <el-form-item label="处理状态">
          <el-radio-group v-model="processForm.status">
            <el-radio :label="1">处理中</el-radio>
            <el-radio :label="2">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理结果">
          <el-input
            v-model="processForm.handleResult"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果或备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProcess">确认</el-button>
      </template>
    </el-dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FeedbackVO, FeedbackStatsVO } from '@/api/miniprogram/feedback'
import {
  getFeedbackPage,
  getFeedback,
  getFeedbackStats,
  handleFeedback,
  deleteFeedback
} from '@/api/miniprogram/feedback'

defineOptions({ name: 'MiniProgramFeedback' })

// 响应式数据
const loading = ref(false)
const feedbackList = ref<FeedbackVO[]>([])
const stats = ref<FeedbackStatsVO>({
  totalFeedbacks: 0,
  pendingFeedbacks: 0,
  handledFeedbacks: 0,
  todayNewFeedbacks: 0,
  typeStats: {
    bug: 0,
    suggestion: 0,
    complaint: 0,
    other: 0
  }
})

// 搜索表单
const searchForm = ref({
  keyword: '',
  type: '',
  status: undefined as number | undefined
})

// 分页
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框
const detailVisible = ref(false)
const currentFeedback = ref<FeedbackVO | null>(null)

// 处理对话框
const processVisible = ref(false)
const processForm = ref({
  id: 0,
  status: 1,
  handleResult: ''
})

// 获取反馈列表
const getFeedbackList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }
    const response = await getFeedbackPage(params)
    if (response.code === 200) {
      // 适配后端返回的数据结构
      if (response.data && response.data.records) {
        feedbackList.value = response.data.records || []
        pagination.value.total = response.data.total || 0
      } else if (response.data && Array.isArray(response.data)) {
        feedbackList.value = response.data
        pagination.value.total = response.data.length
      } else {
        feedbackList.value = []
        pagination.value.total = 0
      }
    }
  } catch (error) {
    console.error('获取反馈列表失败:', error)
    ElMessage.error('获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatsData = async () => {
  try {
    const response = await getFeedbackStats()
    if (response.code === 200) {
      stats.value = response.data || {
        totalFeedbacks: 0,
        pendingFeedbacks: 0,
        handledFeedbacks: 0,
        todayNewFeedbacks: 0,
        typeStats: {
          bug: 0,
          suggestion: 0,
          complaint: 0,
          other: 0
        }
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  getFeedbackList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    type: '',
    status: undefined
  }
  pagination.value.current = 1
  getFeedbackList()
}

// 查看详情
const handleViewDetail = async (row: FeedbackVO) => {
  try {
    const response = await getFeedback(row.id!)
    if (response.code === 200) {
      currentFeedback.value = response.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取反馈详情失败:', error)
    ElMessage.error('获取反馈详情失败')
  }
}

// 处理反馈
const handleProcess = (row: FeedbackVO) => {
  processForm.value = {
    id: row.id!,
    status: 1,
    handleResult: ''
  }
  processVisible.value = true
}

// 确认处理
const confirmProcess = async () => {
  try {
    const response = await handleFeedback(processForm.value.id, {
      status: processForm.value.status,
      handleResult: processForm.value.handleResult
    })
    if (response.code === 200) {
      ElMessage.success('处理成功')
      processVisible.value = false
      getFeedbackList()
      getStatsData()
    }
  } catch (error) {
    console.error('处理反馈失败:', error)
    ElMessage.error('处理反馈失败')
  }
}

// 删除反馈
const handleDelete = async (row: FeedbackVO) => {
  try {
    await ElMessageBox.confirm('确定要删除这条反馈吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteFeedback(row.id!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getFeedbackList()
      getStatsData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除反馈失败:', error)
      ElMessage.error('删除反馈失败')
    }
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.value.size = size
  pagination.value.current = 1
  getFeedbackList()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  getFeedbackList()
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    bug: 'danger',
    suggestion: 'success',
    complaint: 'warning',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    bug: 'Bug反馈',
    suggestion: '功能建议',
    complaint: '投诉',
    other: '其他'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'danger',
    1: 'warning',
    2: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未处理',
    1: '处理中',
    2: '已处理'
  }
  return statusMap[status] || '未知'
}

// 初始化
onMounted(() => {
  getFeedbackList()
  getStatsData()
})
</script>